Xbasic

FOR ... NEXT, CONTINUE, EXIT FOR

IN THIS PAGE

Syntax

FOR Variable_Name = Start_Value TO End_Value [ STEP Increment_Value ] [ statements ] [ CONTINUE ] [ statements ] [ EXIT FOR ] NEXT [ Variable_Name ]

Arguments

Variable_Name

The name of the numeric variable that counts iterations through the loop.

Start_Value

The initial value of Variable_Name.

End_Value

When Variable_Name exceeds End_Value the loop ends.

Increment_Value

Optional. Default = 1. An value equal to 0 will cause a permanent loop. When Start_Value exceeds End_Value the STEP argument must be used with an negative Increment_Value.

Description

Repeats a series of Xbasic statements a specified number of times.

Discussion

FOR ... NEXT is used to repeat a series of Xbasic statements a specified number of times. The statements inside a FOR loop, between the FOR and NEXT statements, are executed ( Start_Value - End_Value ) / Increment_Value times or until an EXIT FOR statement is reached. Each FOR ... NEXT statement parameter must be an integer value. The counter or iterator is a numeric variable ( Variable_Name ) that is changed each time the loop is repeated. By default, the counter variable is incremented by 1 from the Start Value to the End_Value, where Start_Value is less than or equal to End_Value. When the End_Value is reached or when End_Value is zero (0), the loop terminates. To change the amount by which the counter variable is incremented, add the STEP statement and an Increment Value. The Increment_Value must be an integer greater than or equal to 1, or less than or equal to -1. For example, to count through the odd numbers from 1 to 10, use the following statement:

FOR i = 1 TO 10 STEP 2
    trace.writeln( STR(i) )
NEXT

When including a negative Increment_Value (e.g., -1) the Start_Value and End_Value should be reversed, to proceed from a higher value to a lower value.

FOR i = 10 TO 1 STEP -2
    trace.writeln( STR(i) )
NEXT

Adding the counter VariableName after the NEXT statement is necessary only when working with two or more nested FOR ... NEXT loops.

FOR x = 1 TO 50
    FOR y = 1 TO 50
        trace.writeln( "x:" + ltrim( str(x) ) + " y:" + ltrim( str(y) ) )
    NEXT y
NEXT x
The keyword CONTINUE is available only in Version 6 and above. It will branch to the next evaluation of the loop.

Example

This script counts down from 10 to 1.

trace.writeln("Count down...")
FOR i = 10 TO 1 STEP -1
    trace.writeln( LTRIM( STR(i) ) )
NEXT
trace.writeln("Blastoff!!!")

See Also